import "./reset.css";
import dayjs from "dayjs";
import editForm from "../form/index.vue";
import { message } from "@/utils/message";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps, RoleFormItemProps } from "../utils/types";
import {getKeyList, isAllEmpty, hideTextAtIndex, deviceDetection} from "@pureadmin/utils";
import { getSystemViewList} from "@/api/system";
import {ElMessageBox} from "element-plus";
import {type Ref, h, ref, toRaw, watch, computed, reactive, onMounted} from "vue";

export function useDict(tableRef: Ref, treeRef: Ref) {
  const form = reactive({
    dict_id: "",
    label: "",
    value: "",
    keyword: "",
    status: ""
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const selectCateId = ref('');
  const dataList = ref([]);
  const viewList = ref([]);
  const userList = ref([]);
  const roleList = ref([]);
  const fieldList = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const treeLoading = ref(true);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,pageSizes: [20, 40, 60,100,300,500],
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {label: "勾选列",type: "selection", fixed: "left", reserveSelection: true},
    {label: "ID", prop: "id", width: 90},
    {label: "视图名称", prop: "view_name", minWidth: 130},
    {
      label: "视图类型",
      prop: "view_type",//{{viewList}}[ { "label": "订单视图", "id": "order" }, { "label": "产品价格表视图", "id": "price" } ]
      width: 130,
      cellRenderer: scope => (
        <span>{viewList.value.find(x=>x.id == scope.row.view_type)?.label} </span>
      )
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={2}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {label: "创建人", prop: "creator",width:160},
    {label: "创建时间", minWidth: 90, prop: "created_at"},
    {label: "更新时间", prop: "updated_at",width:120},
    {label: "操作", fixed: "right", width: 180, slot: "operation"}
  ];

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 0 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.label
      }</strong>视图吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        getSystemViewList(row,"put").then(res=>{
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          message(`已${row.status === 2 ? "停用" : "启用"}${row.label}选项`, {
            type: "success"
          });
        })
      }).catch(() => {
        row.status === 2 ? (row.status = 1) : (row.status = 2);
      });
  }

  function handleUpdate(row) {
    console.log(row);
  }

  function handleDelete(row) {
    getSystemViewList({id:row.id},"delete").then(res=>chores(row,res,'删除',()=>{}))
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val
    onSearch()
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    onSearch()
  }


  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    getSystemViewList({},"delete").then(res=>function (){
      message(`已删除用户编号为 ${getKeyList(curSelected, "id")} 的数据`, {
        type: "success"
      });
      tableRef.value.getTableRef().clearSelection();
      onSearch();
    })
  }

  async function onSearch() {
    loading.value = true;
    form.page = pagination.currentPage
    form.limit = pagination.pageSize
    const { data } = await getSystemViewList(toRaw(form));

    dataList.value = data.data;
    userList.value = data.user_list;
    roleList.value = data.role_list;
    fieldList.value = data.fields;
    viewList.value = data.fields.map(x=>({label:x.view_type,id:x.table_name}))
    viewList.value = viewList.value.filter((item, index, self) =>
        index === self.findIndex((i) => (
          i.id === item.id // 基于id去重
        ))
    );

    pagination.total = data.total;
    pagination.pageSize = data.per_page;
    pagination.currentPage = data.from;
    console.log(4444,data,data.total)
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    form.view_type = "";
    onSearch();
  };

function switchDict(id){
  form.view_type = id;
  selectCateId.value = id;
  onSearch();
}

  function chores(curData,res,title,done) {
    if(res.code===0){
      message(`您${title}了视图名称为${curData.view_name}的这条数据`, {
        type: "success"
      });
      done(); // 关闭弹框
      onSearch(); // 刷新表格数据
    }else{
      message(`${title}失败，原因：${res.message}`, {
        type: "error"
      });
    }
  }
  function openDialog(viewList,title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}视图信息`,
      props: {
        formInline: {
          title,
          view_type: row?.view_type ?? selectCateId.value,
          view_name: row?.view_name ?? "",
          status: row?.status ?? 1,
          range_type: row?.range_type ?? '1',
          viewList:viewList??[],
          userList:userList??[],
          roleList:roleList??[],
          range_ids:row?.range_ids??[],
          fields:row?.fields??fieldList.value.filter(x=>x.field_disable==2 &&x.field_default==1).map(x=>x.field_name),
          fieldList:fieldList??[],
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        // function chores() {
        //   message(`您${title}了用户名称为${curData.username}的这条数据`, {
        //     type: "success"
        //   });
        //   done(); // 关闭弹框
        //   onSearch(); // 刷新表格数据
        // }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData,title);
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              getSystemViewList(curData,"post").then(res=>chores(curData,res,title,done))
            } else {
              curData.id = row.id
              // 实际开发先调用修改接口，再进行下面操作
              getSystemViewList(curData,"put").then(res=>chores(curData,res,title,done))
            }
          }
        });
      }
    });
  }

  onMounted(async () => {
    onSearch();
  });

  return {
    form,getSystemViewList,
    loading,
    columns,
    dataList,
    treeLoading,
    selectedNum,
    pagination,
    deviceDetection,viewList,switchDict,selectCateId,userList,roleList,fieldList,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
  };
}
